<?php
/**
 * +----------------------------------------------------------------------
 * | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
 * +----------------------------------------------------------------------
 * | File name: RepaySummaryInteface.php
 * +----------------------------------------------------------------------
 * | Author: lijiafei
 * +----------------------------------------------------------------------
 * | Description:
 * +----------------------------------------------------------------------
 * | Others: 请求资方平台和公共平台的接口traits
 * +----------------------------------------------------------------------
 * | History:
 * +----------------------------------------------------------------------
 * | 1.Date: 2019/3/11 Author: lijiafei Modification: 创建
 * +----------------------------------------------------------------------
 */

namespace App\Models\Traits;


use App\Constant\ThirdCommonCode;
use App\Constant\ThirdMoneyCode;
use App\Events\CollectionReceiptEvent;
use App\Events\RepayMentEvent;
use App\Facades\CommonPlatformRequestFacade;
use App\Facades\MoneyPlatformRequestFacade;
use App\Facades\RepayBuckleRequestFacade;
use App\Jobs\RepayCommonJobQueue;
use App\Jobs\RepayJobQueue;
use App\Jobs\RepayMonthJobQueue;
use App\Library\Bank\BankCode;
use App\Models\RepayRecord;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;
use App\Models\User;
use App\Models\UserBankCard;
use App\Models\UserGlobal;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

trait RepaySummaryInteface
{

    /**
     * Description:逐期还,调用队列
     * Author:lijiafei
     * @param RepayRecord $recordInfo
     * @return mixed
     */
    public static function setCurrentRepayJob(RepayRecord $recordInfo,$repayTypeCode = RepayRecord::REPAY_TYPE_MANUAL,$is_vail = 0){
        $month_status = $recordInfo->month->status;
        $common_status = $recordInfo->common->status;
        $money_status = $recordInfo->money->status;
        if($month_status == RepayRecordMonth::STATUS_TWO || $common_status == RepayRecordCommon::STATUS_TWO || $money_status == RepayRecordMoney::STATUS_TWO){
            $returnData['flag'] = false;
            $returnData['msg'] = '正在还款中';
            return $returnData;
        }
        if($is_vail == 0){
            if(RepayRecord::STATUS_TWO == $recordInfo->status){
                $returnData['flag'] = false;
                $returnData['msg'] = '正在还款中';
                return $returnData;
            }
        }

        if(RepayRecord::STATUS_FOUR == $recordInfo->status){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前期已经还款成功';
            return $returnData;
        }
        $flag = self::isBuckle($recordInfo,$repayTypeCode);
        if($flag != 1){
            //京东裸扣不走资方 通知催方
            event(new RepayMentEvent($recordInfo->summary_id));
            return $flag;
        }
        if($money_status == RepayRecordMoney::STATUS_ONE || $money_status == RepayRecordMoney::STATUS_THREE)
        {
            //资方队列
            $res = RepayJobQueue::dispatch($recordInfo->id);
            if($res){
                self::setRepayStatus($recordInfo->id,$recordInfo->uid,$recordInfo->money->summary_id,$recordInfo->money->period,'money',$repayTypeCode);
            }
        }elseif ($money_status == RepayRecordMoney::STATUS_FOUR){

            if($month_status == RepayRecordMonth::STATUS_ONE || $month_status == RepayRecordMonth::STATUS_THREE){
                //月保费队列
                $res = RepayMonthJobQueue::dispatch($recordInfo->id);
                if($res){
                    self::setRepayStatus($recordInfo->id,$recordInfo->uid,$recordInfo->month->summary_id,$recordInfo->month->period,'month',$repayTypeCode);
                }
            }elseif($month_status == RepayRecordMonth::STATUS_FOUR){
                if($common_status == RepayRecordCommon::STATUS_THREE || $common_status == RepayRecordCommon::STATUS_ONE)
                {
                    //公共平台队列
                    $res = RepayCommonJobQueue::dispatch($recordInfo->id);
                    if($res){
                        self::setRepayStatus($recordInfo->id,$recordInfo->uid,$recordInfo->common->summary_id,$recordInfo->common->period,'common',$repayTypeCode);
                    }
                }elseif($common_status == RepayRecordCommon::STATUS_FOUR){
                    $returnData['flag'] = false;
                    $returnData['msg'] = '当前期已经还款成功';
                    return $returnData;
                }
            }
        }
        $returnData['flag'] = true;
        $returnData['msg'] = '正在还款中,请等待';
        return $returnData;
    }


    /**
     * Description:全部还清调队列公共方法 RepayController  and RepaymentController类里面
     * Author:lijiafei
     * @param RepayRecord $recordInfo
     * @param int $code
     * @return mixed
     */
    public static function setAllRepayJob(RepayRecord $recordInfo,$repayTypeCode,$is_vail = 0){
        $common_status = $recordInfo->common->status;
        $money_status = $recordInfo->money->status;

        if(RepayRecordCommon::STATUS_TWO == $common_status || RepayRecordMoney::STATUS_TWO == $money_status){
            $returnData['flag'] = false;
            $returnData['msg'] = '正在还款中';
            return $returnData;
        }

        if($is_vail == 0){
            if(RepayRecord::STATUS_TWO == $recordInfo->status){
                $returnData['flag'] = false;
                $returnData['msg'] = '正在还款中';
                return $returnData;
            }
        }

        if(RepayRecord::STATUS_FOUR == $recordInfo->status){
            $returnData['flag'] = false;
            $returnData['msg'] = '当前期已经还款成功';
            return $returnData;
        }

        $flag = self::isBuckle($recordInfo,$repayTypeCode);
        if($flag != 1){
            //京东裸扣 通知催收
            event(new RepayMentEvent($recordInfo->summary_id));
            return $flag;
        }

        if($money_status == RepayRecordMoney::STATUS_ONE || $money_status == RepayRecordMoney::STATUS_THREE){
            //待处理  失败  统一交给队列处理
            $res = RepayJobQueue::dispatch($recordInfo->id);
            if($res){
                self::setRepayStatus($recordInfo->id,$recordInfo->uid,$recordInfo->summary_id,$recordInfo->period,'money',$repayTypeCode);
            }
        }elseif($money_status == RepayRecordMoney::STATUS_FOUR){
            if($common_status == RepayRecordCommon::STATUS_ONE || $common_status == RepayRecordCommon::STATUS_THREE){
                //请求公共方法
                $res = RepayCommonJobQueue::dispatch($recordInfo->id);
                if($res){
                    self::setRepayStatus($recordInfo->id,$recordInfo->uid,$recordInfo->summary_id,$recordInfo->period,'common',$repayTypeCode);
                }
            }elseif($common_status == RepayRecordCommon::STATUS_FOUR){
                $returnData['flag'] = false;
                $returnData['msg'] = '当前期已经还款成功';
                return $returnData;
            }
        }
        $returnData['flag'] = true;
        $returnData['msg'] = '正在还款中,请等待';
        return $returnData;
    }


    /**
     * Description:请求资方接口
     * Author:lijiafei
     * @param $recordInfo RepayRecord 表的model
     * @param $tradeNo 1 逐期还款 2 全部还清
     * @return bool
     */
    public static function setMoney($recordInfo,$tradeNo){
        $questData = self::getMoneyRequestData($recordInfo);
        $moneyData['loanId'] = $questData['loan_id'];
        $moneyData['merOrderNo'] = $tradeNo;
        $moneyData['currentPeriod'] = $questData['period'];
        $moneyData['totalAmt'] = $questData['totalAmt']; //还款总金额
        $moneyData['principalAmt'] = $questData['amount']; //本金
        $moneyData['interestAmt'] = $questData['lending_money']; //利息
        $moneyData['serviceAmt'] = $questData['repayment_money']; //服务费
        $moneyData['penaltyAmt'] = $questData['fines_money']; //罚息
        $moneyData['operateStatus'] = $questData['operateStatus'];
        $res = MoneyPlatformRequestFacade::setMoneyRepay($moneyData);
        $result = self::saveRequestError('money',$res,$recordInfo->money->id,$moneyData);
        if(!$result){
            return false;
        }
        if(isset($res['data']['resultRepayId'])){
            RepayRecordMoney::where('id',$recordInfo->money->id)->update(['third_repay_id' => $res['data']['resultRepayId']]);
        }
        return true;
    }

    /**
     * Description:月保费接口还款
     * Author:lijiafei
     * @param $month_id int 月保费id
     * @param $month_amount float 月保费
     * @param $loan_id int 借款id
     * @param $trade_no string 订单号
     * @param $period int 期数
     * @param $summary_id int repay_summaries表的id
     * @return mixed
     */
    public static function setMonth($month_id,$month_amount,$loan_id,$trade_no,$period,$summary_id = 0){

        //记录接口请求时间
        if($period == 0 && $summary_id){
            //全部还清
            RepayRecordMonth::where('summary_id',$summary_id)->where('status','<>',RepayRecordMonth::STATUS_FOUR)->whereNull('apply_time')->update(['apply_time' => Carbon::now()->toDateTimeString()]);
        }else{
            RepayRecordMonth::where('id',$month_id) -> update(['apply_time' => Carbon::now()->toDateTimeString()]);
        }
        $monthdata['amount'] = $month_amount;
        $monthdata['loanId'] = $loan_id;
        $monthdata['merOrderNo'] = $trade_no;
        $monthdata['currentPeriod'] = $period;
        $res = MoneyPlatformRequestFacade::setMonthRepay($monthdata);
        $result = self::saveRequestError('month',$res,$month_id,$monthdata);
        if(!$result){
            return false;
        }
        if(isset($res['data']['resultRecordId'])){
            RepayRecordMonth::where('id',$month_id)->update(['third_record_id' => $res['data']['resultRecordId']]);
        }
        return $res;
    }

    /**
     * Description: 公共支付接口还款
     * Author:lijiafei
     * @param $moneyArray array 金额的数组
     * @param $trade_no string 订单号
     * @param $hold_agreement_num string 银行协议号
     * @param $common_id int 公共接口id
     * @param $channel_type string 资方类型
     * @return mixed
     */
    public static function setCommon($moneyArray,$trade_no,$hold_agreement_num,$common_id,$period,$summary_id){
        $summaryInfo = self::select(['loan_id','data_type','loan_channel'])->where('id',$summary_id)->first();

        //记录接口请求时间
        if($period == 0 && $summary_id){
            RepayRecordCommon::where('summary_id',$summary_id)->where('status','<>',RepayRecordCommon::STATUS_FOUR)->whereNull('apply_time')->update(['apply_time' => Carbon::now()->toDateTimeString()]);
        }else{
            RepayRecordCommon::where('id',$common_id) -> update(['apply_time' => Carbon::now()->toDateTimeString()]);
        }
        $is_channel = self::getLoanChannel($summary_id);

        //2019.03.17:11.36 公共的罚息先不扣
//        $totalAmt = bcadd(bcadd(bcadd($moneyArray['lending_money'],$moneyArray['manage_money'],2),$moneyArray['fines_money'],2),$moneyArray['repayment_money'],2);
        //2019.03.17:8.01 改回来了
        $totalAmt = bcadd(bcadd(bcadd($moneyArray['lending_money'],$moneyArray['manage_money'],2),$moneyArray['fines_money'],2),$moneyArray['repayment_money'],2);

        //针对老系统中的白名单用户 有折扣金额的需要减去折扣金额
        $totalAmt = bcsub($totalAmt,$moneyArray['discount_amount'],2);
        if($totalAmt <=0){
            $totalAmt =0;
        }

        $commonData = array();
        if($totalAmt == 0){
            self::setCommonStatus($common_id);
            return 1;
        }else{
            $bizOrderNoPrefix = RepayRecordCommon::getBizOrderNoPrefix($summaryInfo);
            $commonData['thirdPartyAgreementNo'] = $hold_agreement_num;
            $commonData['withholdTradeAmount'] = $totalAmt;
            $commonData['withholdTradeNo'] = $trade_no;
            $commonData['withholdTradeSubject'] = 'repay_common';
            $commonData['bizOrderNoPrefix'] = $bizOrderNoPrefix;
            $commonData['thirdPartyClientId'] = $is_channel == true ? RepayRecordCommon::NEW_COMMON_MER : RepayRecordCommon::OLD_COMMON_MER;//第三方商户号新的数据和老的晋商新光大使用联众,其他的使用蔚商
            $commonData['loanId'] = $summaryInfo->loan_id;
            $res = CommonPlatformRequestFacade::setCommonRepay($commonData);
        }
        $result = self::saveRequestError('common',$res,$common_id,$commonData);
        if(!$result){
            return false;
        }
        RepayRecordCommon::where('id',$common_id)->update(['third_record_id' => RepayRecordCommon::THIRD_RECORD_ID]);
        return $res;
    }

    /**
     * Description:如果金额为0 就直接成功
     * Author:lijiafei
     */
    public static function setCommonStatus($common_id){
        $model = RepayRecordCommon::where('id',$common_id)->first();
        RepayRecordCommon::setCommonSuccessStatus($model);
        $array = ['code' => ThirdCommonCode::CODE_SUCCESS,'msg' => '金额为0'];
        Log::debug('还款:common金额为0' . $common_id);
        return $array;
    }

    /**
     * 封装资方的接口请求数据
     * @param $recordInfo RepayRecord repay_record的model
     * @return  array data
     */
    protected static function getMoneyRequestData($recordInfo){

        $lending_money = $recordInfo->money->lending_money;//利息  提前还清要请求接口再计算
        $repayment_money = $recordInfo->money->repayment_money;//手续费 提前还清要请求接口再计算
        $fines_money = $recordInfo->money->fines_money;//罚息
        $operateStatus = 'R';//操作状态(正常还款R,提前结清J,提前还当期T)
        $period = $recordInfo->period;//期数
        if($recordInfo->pay_off == RepayRecord::PAY_OFF_ONE){
            //判断是否逾期
            $day_num = count_days(Carbon::now()->toDateString(),$recordInfo->normal_date);
            //还当期
            if($day_num < 0){
                $operateStatus = 'T';//提前还当期T
            }else if($day_num > 0){
                //查表计算罚息
                $fines_money = self::getMoneyFines($recordInfo->loan_id,$recordInfo->period);
            }
        }elseif($recordInfo->pay_off == RepayRecord::PAY_OFF_TWO){
            //全部还清
            $operateStatus = 'J';//提前结清J
            //获取实际应该多少期
            $period = RepayRecord::where('summary_id',$recordInfo->summary_id)->where('pay_off',RepayRecord::PAY_OFF_ONE)->where('status','<>',RepayRecord::STATUS_FOUR)->orderBy('period','asc')->value('period');
            //全部还清的话  apply_time时间统一补下
            RepayRecordMoney::where('summary_id',$recordInfo->summary_id)->where('status','<>',RepayRecordMoney::STATUS_FOUR)->whereNull('apply_time')->update(['apply_time' => Carbon::now()->toDateTimeString()]);
            //从提前结清接口从获取数据同步一下
            $moneyData = self::getRepaymentPlan($recordInfo->loan_id,$recordInfo->summary_id);
            $lending_money = $moneyData['lending_money'];
            $fines_money = $moneyData['fines_money'];
            $repayment_money = $moneyData['repayment_money'];
        }
        //更新模型数据
        $money = RepayRecordMoney::find($recordInfo->money->id);
        $money->lending_money = $lending_money;
        $money->fines_money = $fines_money;
        $money->repayment_money = $repayment_money;
        $money->apply_time = Carbon::now()->toDateTimeString();
        $money->save();

        $totalAmt = bcadd(bcadd(bcadd($recordInfo->amount,$lending_money,2),$repayment_money,2),$fines_money,2);
        //返回数据
        $data['totalAmt'] = $totalAmt;
        $data['lending_money'] = $lending_money;
        $data['amount'] = $recordInfo->amount;
        $data['repayment_money'] = $repayment_money;
        $data['period'] = $period;
        $data['fines_money'] = $fines_money;
        $data['operateStatus'] = $operateStatus;
        $data['loan_id'] = $recordInfo->loan_id;
        return $data;
    }


    /**
     * 处理错误信息
     * @param $model_name string 要操作的模型名字
     * @param $info array 接口返回信息
     * @param $id int 表的id
     * @return string info
     */
    protected static function saveRequestError($model_name,$info,$id,$requestData){
        $code_status = $model_name == 'common' ? ThirdCommonCode::CODE_SUCCESS : ThirdMoneyCode::CODE_SUCCESS;
        if ($info['code'] != $code_status) {
            Log::debug('还款:请求' . $model_name . '接口报错:' . json_encode($info,JSON_UNESCAPED_UNICODE));
            Log::debug('还款:请求数据是:'. json_encode($requestData,JSON_UNESCAPED_UNICODE));
            $erroMessage = isset($info['message']) ? $info['message'] : '';
            $model = null;
            $status = 0;
            switch ($model_name){
                case 'month':
                    $model = new RepayRecordMonth();
                    $failure_status = RepayRecord::FAILURE_STATUS_ONE;
                    $status = RepayRecordMonth::STATUS_THREE;
                    break;
                case 'common':
                    $model = new RepayRecordCommon();
                    $failure_status = RepayRecord::FAILURE_STATUS_TWO;
                    $status = RepayRecordCommon::STATUS_THREE;
                    break;
                case 'money':
                    $model = new RepayRecordMoney();
                    $failure_status = RepayRecord::FAILURE_STATUS_THREE;
                    $status = RepayRecordMoney::STATUS_THREE;
                    break;
                default:
                    return false;
                    break;
            }
            DB::beginTransaction();
            try{
                $userInfo = $model->where('id',$id)->first();
                $model->where('id',$id)->update(['status' => $status,'failure' => $erroMessage]);
                RepayRecord::where('id',$userInfo['record_id'])->update(['status' => RepayRecord::STATUS_THREE,'failure_status' => $failure_status,'failure_message' => $erroMessage]);
                UserGlobal::where('uid',$userInfo['uid'])->update(['global_status' => UserGlobal::STATUS_REPAY_FAILURE]);

                //发送失败的短信
                if($userInfo->period == 0){
                    self::sendSettlementFailureSms($userInfo);
                }elseif($userInfo->period != 0){
                    //判断是否是自动还是手动
                    if($userInfo->repay_type == RepayRecord::REPAY_TYPE_MANUAL){
                        //手动
                        self::sendHandleFailureSms($userInfo);
                    }elseif($userInfo->repay_type == RepayRecord::REPAY_TYPE_AUTO){
                        //自动
                        self::sendAotuFailureSms($userInfo);
                    }
                }
                DB::commit();
                event(new CollectionReceiptEvent($userInfo->record_id));
                return false;
            }catch (\Exception $e){
                \Log::debug('还款:接口返回报错,更新错误状态出错' . $e->getFile() . '的' . $e->getLine() . '行中' . $e->getMessage() . '导致此次队列执行失败' . PHP_EOL);
                DB::rollBack();
            }
        }
        Log::debug('还款:' . $model_name . json_encode($info,JSON_UNESCAPED_UNICODE));
        return $info;

    }

    /**
     * Description:判断是否需要裸扣
     * Author:lijiafei
     * @param RepayRecord $recordInfo
     * @param $repayTypeCode
     * @return int|mixed
     */
    public static function isBuckle(RepayRecord $recordInfo,$repayTypeCode){
        //判断是否需要京东裸扣
        $otherBank = UserBankCard::select('id')
            ->where('uid',$recordInfo->uid)
            ->where('hold_agreement_num','<>','')
            ->whereNotNull('hold_agreement_num')
            ->first();
        if(empty($otherBank->id)){
            //京东裸扣
            $res = self::setBuckle($recordInfo,$repayTypeCode);
            return $res;
        }else{
            return 1;
        }
    }

    public static function setBuckle(RepayRecord $recordInfo,$repayTypeCode){
        $summaryInfo = self::where('id',$recordInfo->summary_id)->first();
        //订单号 手机号 users 金额 姓名 user_cert_ocrs 证件号user_cert_ocrs 卡号 user_bank_code 银行code 交通摘要 回调地址
        $money = self::getOrderTotalMoney($summaryInfo,$recordInfo->period);
        $money = bcmul($money,100);//转换为分
        $card_id = RepayRecord::where('id',$recordInfo->id)->value('bank_cards_id');
        $userBankInfo = UserBankCard::select(['card_num','bank_name','card_username','phone_num'])->where('id',$card_id)->first();
        $channelBankCode = BankCode::getJdBankCode($userBankInfo->bank_name);
        $userInfo = User::where('id',$recordInfo->uid)->first();
        $order_id = self::createTradeNo($recordInfo->uid,'buckle');
        $data = [
            'orderId' => $order_id,//订单号
            'mobile' => empty($userBankInfo->phone_num) ? '' : $userBankInfo->phone_num,//手机号
            'transAmount' => $money,//金额 => 分
            'cardOwer' => empty($userBankInfo->card_username) ? "a" : $userBankInfo->card_username,//姓名
            'certNo' => empty($userInfo->cert_no) ? 0 : $userInfo->cert_no,//证件号
            'cardNo' => empty($userBankInfo->card_num) ? 0 : $userBankInfo->card_num,//卡号
            'channelBankCode' => $channelBankCode,//$CCBuserBankInfo['code'],//银行code
            'purposeDesc' => 'buckle_' . $order_id,//交易摘要
            'callbackUrl' => '127.0.0.1'//回调地址
        ];
        $res = RepayBuckleRequestFacade::setBuckleMoney($data);
        if($res['success'] == true){
            if($res['orderStatus'] == RepayRecord::ORDER_STATUS_ING || $res['orderStatus'] == RepayRecord::ORDER_STATUS_SUCCESS){
                //不管是待处理 还是直接处理成功,统一走轮询查询结果
                self::successData($res,$recordInfo,$repayTypeCode);
                $returnData['flag'] = true;
                $returnData['msg'] = '正在还款中,请等待';
                return $returnData;
            }elseif($res['orderStatus'] = RepayRecord::ORDER_STATUS_FAIL){
                self::failData($res,$recordInfo,$repayTypeCode);
                $returnData['flag'] = false;
                $returnData['msg'] = '还款失败,请稍后重试';
                return $returnData;
            }

        }else{
            $res['errorMessage'] = '还款失败';
            self::failData($res,$recordInfo,$repayTypeCode);
            $returnData['flag'] = false;
            $returnData['msg'] = '还款失败,请稍后重试';
            return $returnData;
        }
    }

    /**
     * Description:京东裸扣成功请求处理
     * Author:lijiafei
     */
    protected static function successData(array $res,RepayRecord $recordInfo,$repayTypeCode){
        try{
            DB::beginTransaction();
            //把record表改为2
            self::setRepayStatus($recordInfo->id,$recordInfo->uid,$recordInfo->summary_id,$recordInfo->period,'money',$repayTypeCode);
            //裸扣的订单号,京东的订单号
            $update = [
                'buckle_type' => RepayRecord::BUCKLE_TYPE_ONE,//把record表给为裸扣状态
                'buckle_order_id' => $res['orderId'],
                'buckle_channel_order_id' => $res['channelOrderId'],
            ];
            RepayRecord::where('id',$recordInfo->id)->update($update);
            //更新还款时间
            self::setRepayApplyTime($recordInfo);
            DB::commit();
        }catch (\Exception $e){
            Log::debug('还款:裸扣:接口成功更改状态错误' . $e->getMessage());
            DB::rollBack();
        }
    }

    protected static function setRepayApplyTime(RepayRecord $model){

        $update = [
            'apply_time' => Carbon::now()
        ];
        if(0 == $model->period){
            $where = [
                ['summary_id', '=', $model->summary_id],
                ['status', '<>', RepayRecord::STATUS_FOUR],
            ];
        }else{
            $where = [
                ['record_id', '=', $model->id],
            ];
        }
        RepayRecordMoney::where($where)->update($update);
        RepayRecordMonth::where($where)->update($update);
        RepayRecordCommon::where($where)->update($update);

    }

    /**
     * Description:请求裸扣的获取结果
     * Author:lijiafei
     * @param array $res
     * @param RepayRecord $record
     * @param $repayTypeCode
     * @return mixed
     */
    public static function failData(array $res,RepayRecord $record,$repayTypeCode){
        $update = [
            'status' => RepayRecord::STATUS_THREE,//更改为失败状态
            'failure_message' => $res['errorMessage'],//错误原因
            'failure_status' => RepayRecord::FAILURE_STATUS_FIVE,//裸扣失败
            'buckle_type' => RepayRecord::BUCKLE_TYPE_ONE,
            'buckle_order_id' => $res['orderId'],
            'buckle_channel_order_id' => $res['channelOrderId'],
        ];
        RepayRecord::where('id',$record->id)->update($update);
        //更改用户的全局状态
        UserGlobal::where('uid',$record->uid)->update(['global_status' => UserGlobal::STATUS_REPAY_FAILURE]);
        if($record->apply_number){
            event(new CollectionReceiptEvent($record->id));
        }
        $returnData['flag'] = false;
        $returnData['msg'] = '还款失败';
        return $returnData;
    }



}